use leptos::{ prelude::*, task::spawn_local};
use shq_common::prelude::User;
use shq_web_controls::{use_message, MessageOptions, MessageVariant, ToastPosition, ToasterProvider};
use thaw_utils::ArcOneCallback;
use crate::{components::upload_file::UploadFile, shhr::{del_transaction_file_by_fileid, fetch_abnormal_transaction_by_frid, fetch_flow_run_step, fetch_transaction_abnormal, fetch_transaction_file_by_frid, save_transaction_abnormal_record, save_transaction_file}, workflow::FlowRunList};
use std::{collections::{BTreeMap, HashMap}, f64::consts::E};
use leptos_icons::*;
use icondata as i;
use serde_json::{ Map, Value };
use shq_web_controls::MultiTreeSelect;

#[component]
pub fn Transaction(menu_id: u32) -> impl IntoView {

    let mess = use_message();
    let selected_emnm = RwSignal::new(String::new());
    let selected_emno = RwSignal::new(String::new());
    let selected_emid = RwSignal::new(u32::default());
    let selected_ny = RwSignal::new(u32::default());
    let selected_frid = RwSignal::new(u32::default());
    let showImportModel = RwSignal::new(false);
    let abnormal_ids = RwSignal::new(Vec::<String>::new()); //页面勾选记录
    let open_pdf = RwSignal::new(true);
    let pdfs_map: RwSignal<HashMap<u64, u64>> = RwSignal::new(HashMap::new());

    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let emid = curr_user.with(|u| u.as_ref().map(|u| u.id)).unwrap();
    //获取当前所在流程节点
    let stepids = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{ 
            let stepid = fetch_flow_run_step(frid,emid).await;
            stepid
        }
    );

    //获取展示的异常列表
    let items = Resource::new(move || (), |_| fetch_transaction_abnormal());
    //获取勾选记录
    let abnormal_items = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{ 
            let abnormals = fetch_abnormal_transaction_by_frid(frid).await;
            abnormals
         }
    );
    let sel_abnormal_ids = Memo::new(move |_| {
        let sel_abnormal_ids: Vec<String> = abnormal_items.get()
            .iter()
            .flat_map(|abnormal_id_result| match abnormal_id_result {
                Ok(abnormal_ids) => abnormal_ids.iter()
                    .map(|id| {
                        // 处理转义引号，移除多余的引号
                        let s = format!("{:?}", id);
                        s.trim_matches('"').to_string()
                    })
                    .collect::<Vec<String>>(),
                Err(_) => vec![],
            })
            .collect();
        sel_abnormal_ids
    });
    //获取文件列表
    let pdfs = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{
            let pdf = fetch_transaction_file_by_frid(frid).await;
            pdf
        }
    );
    create_effect(move |_| {
        if let Some(Ok(value)) = pdfs.get() {
            pdfs_map.set(value);
        }
    });

    let save_abnormal_record = Action::new(move|_|{
        let emid = selected_emid.get();
        let emnm = selected_emnm.get();
        let emno = selected_emno.get();
        let ny = selected_ny.get();
        let frid = selected_frid.get();
        let mut abnormal_ids = abnormal_ids.get();
        if abnormal_ids.is_empty() {
            // abnormal_ids = vec![0];
            abnormal_ids = vec![];
        }
        let abnormal_ids_result: Result<Vec<u64>, _> = abnormal_ids.iter()
                .map(|id| id.parse::<u64>())
                .collect();
        let abnormal_ids = match abnormal_ids_result {
                Ok(ids) => ids,
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                    Vec::new()
                }
        };
        async move{
            match save_transaction_abnormal_record(ny,frid,emid,emno,emnm,abnormal_ids).await {
                Ok(_) => {
                    mess.create("保存成功", MessageVariant::Success, MessageOptions::default());
                }
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
        }
    });

    //导入后的回调
    let on_upload = ArcOneCallback::new(
        move |fileId: Vec<u64>| {
            if fileId.len() > 0 {
                pdfs_map.update(|map| {
                    // 找到当前map中最大的key，如map为空则使用0
                    let max_key = map.keys().max().copied().unwrap_or(0);
                    // 新key为最大key+1
                    let new_key = max_key + 1;
                    // 插入新键值对
                    map.insert(new_key, fileId[0]);
                });
                if selected_frid.get() != 0 || selected_emid.get() != 0 {
                    let emid = selected_emid.get();
                    let emnm = selected_emnm.get();
                    let emno = selected_emno.get();
                    let ny = selected_ny.get();
                    let frid = selected_frid.get();
                    spawn_local(async move{
                        match save_transaction_file(ny,frid,emid,emno,emnm,fileId).await {
                            Ok(_) => {
                                mess.create("导入成功", MessageVariant::Success, MessageOptions::default());
                                showImportModel.set(false);
                            }
                            Err(e) => {
                                mess.create(
                                    format!("导入失败：{}", e),
                                    MessageVariant::Error,
                                    MessageOptions::default()
                                );
                            }
                        };
                    });
                } else {
                    // 处理home_visit_empl_id为None的情况
                    mess.create("没有有效的流程ID", MessageVariant::Error, MessageOptions::default());
                }
            }
        }
    );

    //导入模块的展示
    let specialist_management = move || {
        let on_upload=on_upload.clone();
        if showImportModel.get() && (stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3))  {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open  z-50">
                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            showImportModel.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <h3 class="text-lg font-bold">导入交易流水文件</h3>
                        <div class="p-2">
                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                <UploadFile accept=".pdf" on_upload/>
                            </Suspense>
                        </div>
                    </div>
                </dialog>
            })
        }else {
            None
        }
    };


    let on_change = move |values: Vec<String>| {
        abnormal_ids.set(values);
    };

    // create_effect(move |_| {
    //     if let Some(Ok(saved_abnormals)) = abnormal_items.get() {
    //         abnormal_ids.set(saved_abnormals.clone());
    //     }
    // });
    let abnormals = move || {
        view! {
            {move || match items.get(){
                Some(Ok(abnormals)) => {
                    // let sorted_map: BTreeMap<_, _> = abnormal_map.into_iter().collect();
                    let tree_items = StoredValue::new(abnormals.into());
                    view! {
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 h-full flex flex-col">
                            <div class="p-4 border-b border-gray-200 flex items-center gap-2">
                                <Icon
                                    icon=i::AiFilePdfOutlined 
                                    width="20" 
                                    height="20"
                                />
                                <span class="text-lg font-medium">交易流水异常类型</span>
                            </div>
                            <div class="p-4 flex-1 flex flex-col">
                                <div class="flex items-center justify-start mb-4 gap-2 flex-wrap">
                                    <button class="btn btn-primary transition-all"
                                        on:click=move|_|{
                                            if selected_frid.get() == 0 || selected_emid.get() == 0 {
                                                mess.create("请先选择员工！", MessageVariant::Warning,MessageOptions::default());
                                                return;
                                            }
                                            save_abnormal_record.dispatch(());
                                        }
                                    >
                                        {"保存"}
                                    </button>
                                    <button class="btn btn-primary transition-all"
                                        on:click=move|_|{
                                            if selected_frid.get() == 0 || selected_emid.get() == 0 {
                                                mess.create("请选择要导入的用户！", MessageVariant::Success,MessageOptions::default());
                                                return;
                                            }
                                            showImportModel.set(true);
                                        }
                                    >
                                        {"上传交易流水"}
                                    </button>
                                                
                                </div>
                            </div>
                            <div class="flex-1 overflow-y-auto min-h-1">
                                <MultiTreeSelect
                                    tree_items
                                    show_confirm_cancel_btn=false
                                    on_change
                                    values = sel_abnormal_ids.get()
                                />
                            </div>
                            // <div class="space-y-2 overflow-y-auto flex-1 p-1">
                            //     {sorted_map.iter().map(|(id,name)|{
                            //         let id_val = *id;
                            //         let id_str = id.to_string();
                            //         let name_str = name.clone();

                            //         let is_checked = create_memo(move|_|{
                            //             abnormal_ids.get().contains(&id_val)
                            //         });
                            //         let abnormal_ids = abnormal_ids.clone();
                            //         view! {
                            //             <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors">
                            //                 <input 
                            //                     type="checkbox" 
                            //                     value=id_str
                            //                     checked=is_checked
                            //                     class="checkbox checkbox-sm border-gray-400 [--chkbg:theme(colors.indigo.600)] [--chkfg:white] checked:border-indigo-600"
                            //                     on:change={move|ev|{
                            //                         let checked = event_target_checked(&ev);
                            //                         abnormal_ids.update(move|ids|{
                            //                             if checked {
                            //                                 // 仅在不存在时添加，避免重复
                            //                                 if !ids.contains(&id_val) {
                            //                                     ids.push(id_val);
                            //                                     // 保持数组有序
                            //                                     ids.sort_unstable();
                            //                                 }
                            //                             } else {
                            //                                 // 移除指定ID
                            //                                 ids.retain(|&x| x != id_val);
                            //                             }
                            //                         });
                            //                     }}
                            //                 />
                            //                 <div class="flex-1">
                            //                     <span class="font-medium">{name_str}</span>
                            //                 </div>
                            //             </label>
                            //         }
                            //     }).collect::<Vec<_>>()}
                            // </div>
                        </div>
                    }.into_any()
                }
                Some(Err(e)) => {
                    view! {
                        <div class="p-4 text-red-500">
                            {e.to_string()}
                        </div>
                    }.into_any()
                }
                None => {
                    view! {
                        <div class="flex-1 flex items-center justify-center">
                            "正在加载菜单数据..."
                        </div>
                    }.into_any()
                }
            }}
        }
    };


    let remove_by_value = move |target_value: u64| {
        pdfs_map.update(|map| {
            map.retain(|_, &mut v| v != target_value);
        });
    };
    //删除pdf文件
    let del_transaction_file = Action::new(move|&(fileid):&(u64)|{
        async move{
            match del_transaction_file_by_fileid(fileid).await {
                Ok(_) => {
                    // 根据 value 删除所有匹配的键值对
                    remove_by_value(fileid);
                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                }
                Err(e) => {
                    mess.create(
                        format!("删除失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
        }
    });

    let transaction_file = move || {
        view!{
            <div class="flex flex-1 flex-col gap-4 p-4 overflow-hidden bg-gray-50">
                <div class="space-y-4">
                    <div class="h-full min-h-[300px]">
                        {abnormals}
                    </div>
                </div>
                {/* 下方区域：流水明细表 */}
                <div class="space-y-4">
                    {move || {
                        let pdf_map = pdfs_map.get();
                        let sorted_map: BTreeMap<_, _> = pdf_map.into_iter().collect();
                        if sorted_map.is_empty() {
                            view! {
                                <div class="flex flex-col items-center justify-center p-8 text-gray-500">
                                    <Icon icon=i::AiFilePdfOutlined width="48" height="48"/>
                                    <p>暂无PDF文档</p>
                                </div>
                            }.into_any()
                        } else {
                            let pdf_views = sorted_map.iter().map(|(id, name)| {
                                let pdf_id = *id;
                                let pdf_name = name.clone();
                                view! {
                                    <div class="collapse collapse-arrow bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                                        <input 
                                            type="checkbox"
                                            class="peer"
                                            checked=move || open_pdf.get()
                                            on:change=move |e| {
                                                let checked = event_target_checked(&e);
                                                // 可以在这里处理展开/折叠状态
                                                open_pdf.set(checked);
                                                if checked {
                                                    open_pdf.set(false);
                                                }
                                            }
                                        />
                                        <div class="collapse-title p-4 flex items-center gap-2 text-lg font-medium">
                                            <Icon icon=i::AiFilePdfOutlined width="20" height="20"/>
                                            <span>{format!("交易流水明细表 {}", pdf_id)}</span>
                                        </div>
                                        <div class="collapse-content">
                                            <button class="btn btn-error btn-outline btn-sm transition-all"
                                                on:click=move |_| {
                                                    if stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3){
                                                        // 在这里添加删除PDF的逻辑
                                                        del_transaction_file.dispatch(pdf_name);
                                                    }
                                                }
                                            >
                                                <Icon icon=i::AiDeleteOutlined width="16" height="16"/>
                                                {"删除"}
                                            </button>
                                            <div class="flex-1 bg-gray-50 flex items-center justify-center min-h-[400px]">
                                                <object 
                                                    data={format!("/binary_file/{}", pdf_name)} 
                                                    type="application/pdf" 
                                                    class="w-full h-full min-h-[800px]"
                                                >
                                                    <div class="flex flex-col items-center justify-center h-full text-gray-500 text-lg p-8">
                                                        <Icon icon=i::AiFilePdfOutlined width="48" height="48"/>
                                                        <p>无法加载PDF文档 {pdf_id}</p>
                                                    </div>
                                                </object>
                                            </div>
                                        </div>
                                    </div>
                                }
                            }).collect_view();
                            view! {
                                <div class="space-y-4">
                                    {pdf_views}
                                </div>
                            }.into_any()
                        }
                    }}
                </div>
            </div>
        }
    };

    let on_row_select_change = ArcOneCallback::new(
        move |select_rows:Option<Map<String,Value>>|{
            if let Some(rows) = select_rows{
                if let Some(Value::Number(value)) = rows.get("ny") {
                    if let Some(ny) = value.as_u64().map(|x| x as u32) {
                        selected_ny.set(ny);
                    }
                }
                if let Some(Value::Number(value)) = rows.get("frid"){
                    if let Some(frid) = value.as_u64().map(|x| x as u32){
                        selected_frid.set(frid);
                    }
                }
                if let Some(Value::Number(value)) = rows.get("emid"){
                    if let Some(emid) =  value.as_u64().map(|x| x as u32){
                        selected_emid.set(emid);
                    }
                }
                if let Some(Value::String(emnm_value)) = rows.get("emnm") {
                    selected_emnm.set(emnm_value.clone());
                }
                if let Some(Value::String(emno_value)) = rows.get("emno") {
                    selected_emno.set(emno_value.clone());
                }
            }
        }
    );

    view!{
         <div class="flex flex-1 w-full h-full overflow-hidden bg-white">
            <div class="flex flex-col w-1/3 bg-gray-100 border-r border-gray-300">
                <div class="flex-1 p-4">
                    <FlowRunList menu_id wfid=2u32 on_row_select_change/>
                </div>
            </div>
            <div class="flex flex-col flex-1 bg-gray-100 border-r border-gray-100 overflow-y-auto ">
                <div class="flex-1 p-4">
                    <Suspense fallback=|| view! { <progress class="progress progress-primary w-56"></progress> }>
                        {transaction_file}
                    </Suspense>
                </div>
            </div>
            // 提示信息容器
            <ToasterProvider position=ToastPosition::TopStart>
                {specialist_management}
            </ToasterProvider>
        </div>
    }
}
